/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.common.prometheus.builder;

import com.dsms.common.util.PrometheusUtils;
import lombok.Data;

import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Data
public class RangeQueryBuilder implements QueryBuilder {
    private static final String TARGET_URI_PATTERN_SUFFIX = "/api/v1/query_range?query=#{query}&start=#{start}&end=#{end}&step=#{step}";

    private static final String START_TIME_EPOCH_TIME = "start";
    private static final String END_TIME_EPOCH_TIME = "end";
    private static final String STEP_TIME = "step";
    private static final String QUERY_STRING = "query";


    private String targetUriPattern;
    private Map<String, Object> params = new HashMap<>();

    public RangeQueryBuilder(String prometheusUrl) {
        targetUriPattern = prometheusUrl + TARGET_URI_PATTERN_SUFFIX;
    }

    public RangeQueryBuilder withQuery(String query) {
        params.put(QUERY_STRING, URLEncoder.encode(query, StandardCharsets.UTF_8));
        return this;
    }

    public RangeQueryBuilder withStartEpochTime(long startTime) {
        params.put(START_TIME_EPOCH_TIME, startTime);
        return this;
    }

    public RangeQueryBuilder withEndEpochTime(long endTime) {
        params.put(END_TIME_EPOCH_TIME, endTime);
        return this;
    }

    public RangeQueryBuilder withStepTime(String step) {
        params.put(STEP_TIME, step);
        return this;
    }

    public URI build() {
        return URI.create(PrometheusUtils.namedFormat(targetUriPattern, params));
    }

    public URI build(String promQL, long startTimeStamp, long endTimeStamp, String step) {
        return this.withQuery(promQL)
                .withStartEpochTime(startTimeStamp)
                .withEndEpochTime(endTimeStamp)
                .withStepTime(step)
                .build();
    }

    public URI build(String promQL, long startTimeStamp, long endTimeStamp) {
        return this.withQuery(promQL)
                .withStartEpochTime(startTimeStamp)
                .withEndEpochTime(endTimeStamp)
                .withStepTime(String.valueOf(Math.max((int) ((endTimeStamp - startTimeStamp) / 250), 1)))
                .build();
    }

}
